<template>
  <div class="Card">
    <!-- 头像 -->
    <div class="avatar-main" v-if="!stakingState">
      <div class="avatar-inline">
        <img class="avatar" alt="Avatar" src="../../../assets/images/png/avatar.png" />
        <P>SCT</P>
      </div>
      
    </div>

    <div
      class="avatar-main d-flex justify-center align-center"
      style="flex-direction: column"
      v-else
    >
      <div class="avatar-inline">
        <img
          class="avatar"
          alt="Avatar"
          src="https://gss0.baidu.com/9vo3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/a2cc7cd98d1001e900e51e21bb0e7bec55e797c6.jpg"
        />
        <P>SuperCells</P>
      </div>
      <v-icon color="#AC8250" size="24">{{ icons.mdiClose }}</v-icon>
      <div class="avatar-inline">
        <img
          class="avatar"
          alt="Avatar"
          src="https://gss0.baidu.com/9vo3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/a2cc7cd98d1001e900e51e21bb0e7bec55e797c6.jpg"
        />
        <P>AA{{ $t("Page.Staking.supplier") }}</P>
      </div>
    </div>

    <!-- 价格卡片 -->
    <div class="price-card">
      <v-container class="grey">
        <v-row no-gutters>
          <v-col cols="12" z sm="6">
            <div class="price-card-text">
              <p class="Subtitle">{{ $t("Page.Staking.Locked") }}</p>
              <p class="price">{{ currentPledgeCount | numFormats }}</p>
            </div>
          </v-col>
          <v-divider vertical></v-divider>
          <v-col cols="12" z sm="6">
            <div class="price-card-text" style="text-align: right">
              <p class="Subtitle">staking {{ $t("Page.Staking.cycle") }}</p>
              <div>
                <span class="price">{{ day }} </span>
                <span class="Subtitle">{{ $t("Page.Staking.day") }}</span>
              </div>
            </div>
          </v-col>
        </v-row>
      </v-container>
    </div>

    <div style="width: 100%; padding: 10px 20px">
      <div class="pa-3" v-if="!stakingState && model === 'SCT'">
        <v-btn outlined block color="rgb(173, 130, 80)" @click="stakingState = true">staking</v-btn>
      </div>

      <div class="py-3" v-if="!currentPledgeCount && model === 'Supplier'">
        <v-btn
          elevation="0"
          block
          color="rgb(173, 130, 80)"
          style="color: #fff"
          @click="handlePledge"
          >Staking</v-btn
        >
      </div>

      <div
        class="text-hide"
        :style="actionHide ? 'height: 105px;' : 'height: auto;'"
        v-if="!stakingState && model === 'SCT'"
      >
        <p class="text-left">{{ $t("Page.Staking.rule") }}:</p>
        <p class="text-left">1、{{ $t("Page.Staking.rule1") }}</p>
        <p class="text-left">2、{{ $t("Page.Staking.rule2") }}</p>
        <p class="text-left">3、{{ $t("Page.Staking.rule3") }}</p>
        <p class="text-left">4、{{ $t("Page.Staking.rule4") }}</p>
        <p class="text-left">5、{{ $t("Page.Staking.rule5") }}</p>
      </div>
      <p class="hide" @click="actionHide = !actionHide" v-if="!stakingState && model === 'SCT'">
        {{ actionHide ? $t("Page.Staking.open") : $t("Page.Staking.putAway") }}
        <v-icon color="#AC8250" size="24">
          {{ actionHide ? icons.mdiChevronDoubleDown : icons.mdiChevronDoubleUp }}</v-icon
        >
      </p>
    </div>

    <div class="d-flex pa-4 justify-space-between align-center" v-if="currentPledgeCount">
      <div class="input-number d-flex align-center">
        <div class="character d-flex justify-center align-center" style="background: #fde7e7">
          <v-icon
            color="#870000"
            size="20"
            :disabled="endTime > currentTime"
            @click="changePrice(1)"
          >
            {{ icons.mdiMinus }}
          </v-icon>
        </div>
        <v-divider vertical class="mx-2"></v-divider>
        <div class="character d-flex justify-center align-center" style="background: #e2f8e3">
          <v-icon
            color="#115914"
            size="20"
            :disabled="endTime < currentTime"
            @click="changePrice(2)"
          >
            {{ icons.mdiPlus }}
          </v-icon>
        </div>
      </div>

      <div style="text-align: right; color: #000">
        <p class="caption">{{ $t("Page.Staking.RemainingTime") }} (JST)</p>
        <p class="caption">{{ endTime ? formatJSTDate(endTime) : "--" }}</p>
      </div>
    </div>

    <div
      class="annualized d-flex justify-space-between align-center mx-4 pa-2 font-weight-bold"
      v-if="model === 'Supplier'"
    >
      <p class="caption colorText">{{ $t("Page.Staking.annualizedReturn") }}</p>
      <p class="h6 colorText">{{ apy }}%</p>
    </div>

    <div class="income pa-4" v-if="model === 'Supplier'">
      <p class="caption">{{ $t("Page.Staking.income") }} (SCT)</p>
      <div class="d-flex justify-space-between align-center">
        <p class="font-weight-bold" style="font-size: 22px; color: #000">
          {{ currentPledgeReward }}
        </p>
        <v-btn
          rounded
          elevation="0"
          color="#ab8251"
          class="px-4"
          style="color: #fff; margin: 0; width: 120px"
          :disabled="!currentPledgeReward"
          @click="getReward"
        >
          {{ $t("Page.Staking.receive") }}
        </v-btn>
      </div>
    </div>

    <Dialog
      ref="Dialog"
      v-if="isActive"
      :currentPledgeCount="currentPledgeCount"
      :dialogState="dialogState"
      :apy="apy"
      :pond="pondList[day]"
      @pledgeSuccess="pledgeSuccess"
    />
  </div>
</template>

<script>
import { mdiChevronDoubleDown, mdiClose, mdiPlus, mdiMinus, mdiChevronDoubleUp } from "@mdi/js";
import { InitPledgeContractSigner, numFormat, request } from "../../../utils/wallet";
import Dialog from "../components/dialog.vue";
import { InitPledgeContract, BigNumberToString } from "../../../utils/wallet";
import { formatJSTDate } from "../../../utils/date";
export default {
  name: "Card",
  components: { Dialog },
  props: {
    model: {
      type: "SCT" | "Supplier",
      default: "SCT",
    },
    day: {
      type: String,
      default: "30",
    },
  },
  data() {
    return {
      actionHide: true,
      stakingState: false,
      SupplierStakingState: false,
      isActive: false,
      icons: {
        mdiChevronDoubleDown,
        mdiClose,
        mdiMinus,
        mdiPlus,
        mdiChevronDoubleUp,
      },
      price: 0,
      pondList: { 30: 1, 90: 2, 180: 3 },
      endTime: "",
      totalStake: "",
      balance: "--",
      currentPledgeCount: "--",
      // 质押弹窗状态，可选值为 pledge | cancelPledge
      dialogState: "pledge",
      apy: "--",
      currentPledgeReward: "--",
      PledgeContract: null,
      currentTime: new Date().getTime(),
    };
  },
  filters: {
    numFormats(val) {
      return numFormat(val);
    },
  },
  async mounted() {
    setTimeout(async () => {
      if (!this.ethAddress) return;
      this.changeOverlay(true);
      try {
        const PledgeContract = InitPledgeContract();
        this.PledgeContract = PledgeContract;
        await this.getPledgeContract();
        await this.getStakes();
        await this.queryReward();
      } catch (error) {
        this.changeOverlay(false);
        this.changeSnackbar({ isOpen: true, title: this.$t("Page.Staking.hint") });
        console.log(error);
      }

      this.changeOverlay(false);
    }, 2000);
  },
  methods: {
    formatJSTDate(val) {
      return formatJSTDate(val);
    },
    handlePledge() {
      this.isActive = true;

      setTimeout(() => {
        this.$refs.Dialog.dialog = true;
      }, 100);
    },

    /**
     * @调用领取弹出框
     */
    changePrice(state) {
      this.dialogState = state === 1 ? "cancelPledge" : "pledge";
      this.isActive = true;
      setTimeout(() => {
        this.$refs.Dialog.dialog = true;
      }, 100);
    },

    /**
     * @质押成功回调
     */
    async pledgeSuccess() {
      await request();
      await this.getPledgeContract();
      await this.getStakes();
      await this.queryReward();
      this.changeSnackbar({ isOpen: true, title: "质押成功" });
    },

    /**
     * @查询当前池子状态
     */
    async getPledgeContract() {
      //返回池子当前的状态
      const result = await this.PledgeContract.timeStages(this.pondList[this.day]);
      // 池子结束时间

      if (result["endTime"].toString().length === 10) {
        this.endTime = result["endTime"].toString() * 1000;
      } else {
        this.endTime = result["endTime"].toString();
      }

      //获取全体
      this.totalStake = BigNumberToString(result["totalStake"], 18);
      //年利率
      this.apy = BigNumberToString(result["apy"], 0);
    },

    /**
     * @查询质押
     */
    async getStakes() {
      const result = await this.PledgeContract.stakes(this.ethAddress, this.pondList[this.day]);
      this.currentPledgeCount = Number(BigNumberToString(result["stakeAmount"], 18));
    },

    /**
     * @领取收益
     */
    async getReward() {
      this.changeOverlay(true);
      try {
        const PledgeContract = InitPledgeContractSigner();
        await PledgeContract.claim(this.pondList[this.day]);
        await request(1000 * 13);
        await this.getPledgeContract();
        await this.getStakes();
        await this.queryReward();
      } catch (error) {
        console.log(error);
      }

      this.changeOverlay(false);
    },

    /**
     * @查询收益
     */
    async queryReward() {
      const reward = await this.PledgeContract.queryReward(
        this.ethAddress,
        this.pondList[this.day]
      );
      if (!Number(reward.toString())) {
        this.currentPledgeReward = 0;
        return;
      }
      this.currentPledgeReward = Number(BigNumberToString(reward, 18)).toFixed(5);
      console.log(reward);
    },
  },
};
</script>

<style lang="scss" scoped>
.Card {
  flex-shrink: 0;
  width: 300px;
  min-height: 400px;
  background: #fff;
  background-image: url("../../../assets/images/png/image.png@2x.png");
  background-repeat: no-repeat;
  background-size: 100%;
  border-radius: 8px;
  .avatar-main {
    padding: 30px 0 0 20px;
    z-index: 1;

    .avatar-inline {
      display: flex;
      align-items: center;
      width: 40px;
      height: 40px;
      border-radius: 99px;
      // overflow: hidden;
      .avatar {
        width: 90%;
        object-fit: cover;
        object-position: 50% 20%;
      }
      p {
        margin-left: 20px;
        color: #000;
        font-size: 18px;
        font-weight: 600;
      }
    }
  }

  .price-card {
    width: 90%;
    margin-left: 5%;
    margin-top: 20px;
    height: 80px;
    border-radius: 5px;
    background: #fff;
    background-image: url("../../../assets/images/png/price.png");
    background-repeat: no-repeat;
    background-size: 100% 100%;
    .grey {
      height: 100%;
      .price-card-text {
        display: flex;
        flex-direction: column;
        justify-content: center;
        height: 56px;
        .Subtitle {
          font-size: 13px;

          color: rgba(79, 79, 79, 1);
        }

        .price {
          font-size: 22px;
          font-weight: 600;
          color: #000;
        }
      }
    }
  }

  .text-hide {
    height: 105px;
    overflow: hidden;
    margin-top: 20px;
    font-size: 14px;
    font-weight: 500;
    color: #000;
  }
  .hide {
    width: 100%;
    padding: 10px 0;
    text-align: center;
    cursor: pointer;
    color: rgb(173, 130, 80);
  }
  .colorText {
    color: rgba(173, 130, 80, 1);
  }

  .input-number {
    width: 66px;
    height: 30px;
    padding: 3px;
    border-radius: 5px;
    border: 1px solid rgba(0, 0, 0, 0.15);
    .character {
      height: 20px;
      width: 20px;
      border-radius: 5px;
      cursor: pointer;
    }
  }

  .annualized {
    border-radius: 5px;
    border: 0.5px solid rgba(173, 130, 80, 0.2);
  }
}
</style>
